package com.wbao.dianniu.ui;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.db.DbManager;
import com.wbao.dianniu.db.UserInfo;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

/**
 * 登录
 * 
 * @author yejianjun
 * 
 */
public class LoginActivity extends Activity implements OnClickListener, ILoginListener {

	private Button loginBtn;
	private EditText mUserText, mPasswordText;
	private TextView registerTV, forgetTV;
	private LoginManager manager;
	private YWIMKit mIMKit;
	 private Dialog pDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 系统版本大于19
			Utils.setTranslucentStatus(this,true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
		}
		
		init();
		manager = new LoginManager(this);
		manager.addLoginListener(this);
	}
	
	private void init() {
		loginBtn = (Button) findViewById(R.id.login_btn);
		mUserText = (EditText) findViewById(R.id.username);
		mPasswordText = (EditText) findViewById(R.id.password);
		registerTV = (TextView) findViewById(R.id.login_register);
		forgetTV = (TextView) findViewById(R.id.login_forgetPassword);
		loginBtn.setOnClickListener(this);
		registerTV.setOnClickListener(this);
		forgetTV.setOnClickListener(this);
	}

	private void login() {
		String username = mUserText.getText().toString().trim();
		String password = mPasswordText.getText().toString().trim();
		// 判断用户名
		if (null == username) {
			Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_2));
		} else if (null == password) {
			Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_3));
		} else {
			/** 是否为手机号码 */
			boolean ismobile = username.matches("^(13|15|18|14|17)\\d{9}$");
			if (!ismobile) {
				Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_1));
				return;
			}
			showWaittingDialog();
			// 发送登录请求
			manager.Login(this, username, Utils.Md5(password));
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn:
			login();
			break;
		case R.id.login_register:
			startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
			break;
		case R.id.login_forgetPassword:
			Intent passIntent = new Intent();
			/** type: 1 修改密码，0：忘记密码 */
			passIntent.putExtra(GlobalContext.BUNDLE_DATA, 0);
			passIntent.setClass(LoginActivity.this, ForgetActivity.class);
			startActivity(passIntent);
			break;
		default:
			break;
		}
	}
	
	private void showWaittingDialog(){
		pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
		pDialog.show();
	}
	

	@Override
	public void onFailure(int errorCode, String errorMsg) {
		if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
	}

	@Override
	public void onSuccess(LoginResponse objdata) {
		Utils.saveLoginData(objdata);
		//保存数据库 
		UserInfo userinfo = new UserInfo();
		userinfo.setMobile(mUserText.getText().toString().trim());
		userinfo.setPassword(Utils.Md5(mPasswordText.getText().toString().trim()));
		userinfo.setToken(objdata.getToken());
		DbManager manager = new DbManager(this);
		manager.saveToken(userinfo);
		//登录成功时，登录IM
		loginIM(objdata.getEnvironmentName() + GlobalContext.accountId, Utils.Md5(mPasswordText.getText().toString().trim()));
	}
	
	public void loginIM(String userId,String password){
		if(null == LoginSampleHelper.getInstance().getIMKit()){
			//初始化imik
			LoginSampleHelper.getInstance().initIMKit(userId, getResources().getString(R.string.app_key));
		}
		mIMKit = LoginSampleHelper.getInstance().getIMKit();
		final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
		if(!hisUserId.equals(userId)){	// 两次登录用户不同 先调用登出命令再调用登录命令
			LoginSampleHelper.getInstance().loginOut_Sample();
		}
		//开始登录
		if(null == mIMKit){
			System.out.println("im system init error ");
			return ;
		}
		System.out.println("开始登录IM："+System.currentTimeMillis() + "");
		IYWLoginService loginService = mIMKit.getLoginService();
		YWLoginParam loginParam = YWLoginParam.createLoginParam(userId, password);
		loginService.login(loginParam, new IWxCallback() {
	 
	    	@Override
	    	public void onSuccess(Object... arg0) {
	    		System.out.println("登录成功IM：" +System.currentTimeMillis() + "");
	    		if(null != pDialog && pDialog.isShowing()){
	    			pDialog.dismiss();
	    		}
	    		// 保存自动登录配置信息
	    		saveConfigInfo();
	    		// 成功 界面跳转
	    		startActivity(new Intent(LoginActivity.this, MainActivity.class));
	    		LoginActivity.this.finish();
	    	}
	 
	    	@Override
	    	public void onProgress(int arg0) {
	        	// TODO Auto-generated method stub
	    	}
	 
	    	@Override
	    	public void onError(int errCode, String description) {
	    		if(null != pDialog && pDialog.isShowing()){
	    			pDialog.dismiss();
	    		}
	        	//如果登录失败，errCode为错误码,description是错误的具体描述信息
	    		if(null != description){
	    			Notification.toast(LoginActivity.this, description);
	    		}else{
	    			Notification.toast(LoginActivity.this,  "【登录失败，错误码】：" +errCode );
	    		}
	    		
	    	}
		});
	}
	
	private void saveConfigInfo(){
		SharedPreferencesUtils.init(LoginActivity.this);
//		SharedPreferencesUtils.setAccountId(GlobalContext.accountId+"");
		SharedPreferencesUtils.setUserName(mUserText.getText().toString());
		SharedPreferencesUtils.setPassword(Utils.Md5(mPasswordText.getText().toString().trim()));
		SharedPreferencesUtils.setAutoLoginStatus(true);
	}
	
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
		public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
		@Override
		protected void onDestroy() {
			super.onDestroy();
			if(null != pDialog && pDialog.isShowing()){
				pDialog.dismiss();
			}
		}
		
}
